package mt.dummy;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import mt.Order;
import mt.client.MicroTraderClient;
import mt.comm.ClientComm;

/**
 * The Class MicroTraderClientDummy.
 *
 * @author Grupo 23
 */
public class MicroTraderClientDummy implements MicroTraderClient {

	/** The client. */
	private ClientComm client;

	/** The model for the table. */
	private DefaultTableModel model;

	/** The main Frame. */
	private JFrame main;

	/** The disconnect Button. */
	private JButton disconnect;

	/** The east Panel. */
	private JPanel east;

	/** The center Panel. */
	private JPanel center;

	/** The south Panel. */
	private JPanel south;

	/** The sub buy Button. */
	private JButton subBuy;

	/** The sub sale Button. */
	private JButton subSale;

	/** The see order Button. */
	private JButton seeOrder;

	/** The title Label. */
	private JLabel title;

	/** The north Panel. */
	private JPanel north;

	/** The 1st Panel for East Panel. */
	private JPanel one;

	/** The 2nd Panel for East Panel */
	private JPanel two;

	/** The 3rd Panel for East Panel */
	private JPanel three;

	/** The orders Table. */
	private JTable orders;

	/** A String for the Nickname. */
	private String s;

	/** A String for the Server **/
	private String s1;

	/*
	 * (non-Javadoc)
	 * 
	 * @see mt.client.MicroTraderClient#start(mt.comm.ClientComm)
	 */
	@Override
	public void start(ClientComm clientComm) {
		client = clientComm;
		begin();

	}

	/**
	 * Begin Method For Nickname Insertion.
	 */
	public void begin() {

		s = JOptionPane.showInputDialog("Please Insert Username");
		if (s != null) {
			if (s.trim().equals("")) {
				JOptionPane.showMessageDialog(null,
						"Please Insert a Valid Username");
				begin();
			} else {
				s1 = JOptionPane
						.showInputDialog("Name of the server to connect");
				if (s1 != null) {

					try {
						client.connect(s1, s);

					} catch (UnknownHostException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					GUI();
				}

			}

		} else {
			System.exit(0);
		}

	}

	/**
	 * The GUI method that defines the frame for the client with all the
	 * components it needs to make a purchase or sell an item.
	 */

	// REMOVE EDITABLE FROM CELLS

	/**
	 * 
	 */
	public void GUI() {
		main = new JFrame("MicroTrader - " + s);
		main.setSize(new Dimension(650, 600));
		main.setResizable(false);
		main.setLocationRelativeTo(null);
		main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		main.setVisible(true);
		main.setLayout(new BorderLayout());

		// SOUTH PANEL
		south = new JPanel();
		main.getContentPane().add(south, BorderLayout.SOUTH);
		south.setLayout(new FlowLayout());
		disconnect = new JButton("Disconnect");
		south.add(disconnect);

		// NORTH PANEL
		north = new JPanel();
		title = new JLabel("MICRO TRADER");
		main.getContentPane().add(north, BorderLayout.NORTH);
		north.add(title);

		// EAST PANEL
		east = new JPanel();
		subBuy = new JButton("Submit Buy");
		subSale = new JButton("Submit Sale");
		seeOrder = new JButton("Show Order History");
		main.getContentPane().add(east, BorderLayout.EAST);
		east.setLayout(new GridLayout(3, 1));
		one = new JPanel();
		two = new JPanel();
		three = new JPanel();
		east.add(one);
		one.add(subBuy);
		subBuy.setEnabled(false);
		east.add(two);
		two.add(subSale);
		east.add(three);
		three.add(seeOrder);

		// CENTER PANEL
		String[] col = { "User", "Stock", "Units Available", "Price" };
		model = new DefaultTableModel(0, col.length);
		model.setColumnIdentifiers(col);

		center = new JPanel();
		orders = new JTable(model);
		main.getContentPane().add(center, BorderLayout.CENTER);
		center.add(new JScrollPane(orders));

		// TABLE REFRESH
		if (client.hasNextMessage()) {
			Object[] tmp = { client.getNextMessage() };
			model.addRow(tmp);
		}

		// REPAINT FRAME
		main.repaint();
		main.validate();

		// ORDER TABLE
		orders.getSelectionModel().addListSelectionListener(
				new ListSelectionListener() {

					/*
					 * (non-Javadoc)
					 * 
					 * @see
					 * javax.swing.event.ListSelectionListener#valueChanged(
					 * javax.swing.event.ListSelectionEvent)
					 */
					@Override
					public void valueChanged(ListSelectionEvent e) {
						subBuy.setEnabled(true);
					}
				});

		// ACTIONLISTENER DC
		disconnect.addActionListener(new ActionListener() {

			/*
			 * (non-Javadoc)
			 * 
			 * @see
			 * java.awt.event.ActionListener#actionPerformed(java.awt.event.
			 * ActionEvent)
			 */
			@Override
			public void actionPerformed(ActionEvent e) {
				client.disconnect();
				main.dispose();
				begin();

			}
		});

		// ACTIONLISTENER SUBMIT BUY
		subBuy.addActionListener(new ActionListener() {

			/*
			 * (non-Javadoc)
			 * 
			 * @see
			 * java.awt.event.ActionListener#actionPerformed(java.awt.event.
			 * ActionEvent)
			 */
			@Override
			public void actionPerformed(ActionEvent e) {
				String unit = JOptionPane
						.showInputDialog("How many units you wish to buy?");
				if (unit != null) {
					if (Integer.parseInt(unit) > Integer
							.valueOf((String) orders.getModel().getValueAt(
									orders.getSelectedRow(), 2))) {
						JOptionPane.showMessageDialog(null,
								"Units exceed the existing ones!");
						actionPerformed(e);
					} else {
						Order buy = Order.createBuyOrder(orders.getModel()
								.getValueAt(orders.getSelectedRow(), 0)
								.toString(), (String) orders.getModel()
								.getValueAt(orders.getSelectedRow(), 1),
								Integer.valueOf(unit),
								Double.parseDouble(orders.getModel()
										.getValueAt(orders.getSelectedRow(), 3)
										.toString().toString()));
						client.sendOrder(buy);
						if (Integer.parseInt(unit) == Integer
								.valueOf((String) orders.getModel().getValueAt(
										orders.getSelectedRow(), 2))) {
							model.removeRow(orders.getSelectedRow());
						} else {
							// ORDER EDIT
						}
					}

				}
				subBuy.setEnabled(false);
			}
		});

		// ACTION LISTENER SUBMIT SALE
		subSale.addActionListener(new ActionListener() {

			/*
			 * (non-Javadoc)
			 * 
			 * @see
			 * java.awt.event.ActionListener#actionPerformed(java.awt.event.
			 * ActionEvent)
			 */
			@Override
			public void actionPerformed(ActionEvent e) {
				JTextField nickname = new JTextField(s);
				nickname.setEditable(false);
				JTextField stock = new JTextField();
				JTextField numberOfUnits = new JTextField();
				JTextField pricePerUnit = new JTextField();
				Object[] fields = { "Username", nickname, "Stock", stock,
						"Number Of Units", numberOfUnits, "Price Per Unit",
						pricePerUnit,

				};

				int i = JOptionPane.showConfirmDialog(main, fields, "SALE",
						JOptionPane.OK_CANCEL_OPTION);
				if (i == 0) {

					if (fields != null) {
						if (!(stock.getText().equals("")
								|| numberOfUnits.getText().equals("") || pricePerUnit
								.getText().equals(""))) {

							Object[] temp = { nickname.getText(),
									stock.getText(), numberOfUnits.getText(),
									pricePerUnit.getText() };
							model.addRow(temp);

							Order sell = Order.createSellOrder(
									nickname.getText(), stock.getText(),
									Integer.valueOf(numberOfUnits.getText()),
									Double.valueOf(pricePerUnit.getText()));

							client.sendOrder(sell);
						} else {
							JOptionPane.showMessageDialog(null,
									"Please Insert Valid Inputs");
							actionPerformed(e);

						}
					}

				}

			}

		});

	}
}